package com.yjd.comm.base.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.yjd.comm.util.ServletUtil;

/**
 * 用户会话filter，用于初始化session的一些操作
 * 
 * @author ready
 * 
 */
public class SessionFilter implements Filter {

	private Logger logger = Logger.getLogger(SessionFilter.class);
	public static final String SESSION_ATTRS_MAP = "SESSION_ATTRS_MAP";

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		logger.debug(this + " sessionFilter");
		long start_time = System.currentTimeMillis();
		sessionInit((HttpServletRequest) request, (HttpServletResponse) response);
		long end_time = System.currentTimeMillis();
		long cost_time = end_time - start_time;
		if (cost_time >= 1000) {
			logger.info("初始化session耗时" + cost_time + "比较长，请检查memcached是否有问题!");
		}
		logger.info("session_id = " + ServletUtil.getSessionId((HttpServletRequest) request, (HttpServletResponse) response));
		chain.doFilter(request, response);
		ServletUtil.putRequestSession((HttpServletRequest) request, (HttpServletResponse) response);
	}

	public void sessionInit(HttpServletRequest request, HttpServletResponse response) {
		ServletUtil.initSessionId(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}
